package com.tony.multipledatasource.config;

import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * create by xuxia on 2024/4/7 23:30
 */
@Configuration
public class DataSourceConfig {

    /**
     * 创建mysql数据源，并以此为主数据源
     *
     * @return
     */
    @Primary
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties("spring.datasource.druid.mysql")
    public DataSource mysqlDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 创建oracle数据源
     *
     * @return
     */
    @Bean(name = "oracleDataSource")
    @ConfigurationProperties("spring.datasource.druid.oracle")
    public DataSource oracleDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 通过MySQL数据源获取相应的jdbcTemplate
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "mysqlJdbcTemplate")
    public JdbcTemplate mysqlJdbcTemplate(@Qualifier(value = "mysqlDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 通过oracle数据源获取相应的jdbcTemplate
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "oracleJdbcTemplate")
    public JdbcTemplate oracleJdbcTemplate(@Qualifier(value = "oracleDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
